package cn.jtkj.yh_car_app;

import static android.telephony.PhoneStateListener.LISTEN_CALL_STATE;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.pm.PackageManager;
import android.Manifest;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.flutter.plugin.common.EventChannel;

public class MainActivity extends FlutterActivity {
    private static final String CALL_CHANNEL = "cn.jtkj.yh_car_app/telephony";
    private static final String HOLD_UP_CHANNEL = "cn.jtkj.yh_car_app/holdUp";

    private static final String BDGENUM_CHANNEL = "cn.jtkj.yh_car_app/bdgenumber";
    private MethodChannel callMethodChannel;
    private MethodChannel holdUpMethodChannel;
    private MethodChannel bdgeNumberMethodChannel;
    private boolean isStart = false;
//    private String[] PERMISSIONS = new String[]{
//            Manifest.permission.POST_NOTIFICATIONS
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        callChannel();
        badgeNumberChannel();
    }


    @SuppressLint("Range")
    private long getCallLog() {
        long duration = -1;
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC");
        if (cursor != null && cursor.moveToFirst()) {
            duration = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
            cursor.close(); // 记得关闭游标
            return duration;
        }
        return duration;
    }


    private void callChannel() {
        callMethodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), CALL_CHANNEL);
        callMethodChannel.setMethodCallHandler(
                (call, result) -> {
                    if (call.method.equals("dialPhoneNumber")) {
                        String phoneNumber = call.argument("phoneNumber");
                        if (phoneNumber != null) {
                            dialPhoneNumber(phoneNumber);
                            result.success(null);
                        } else {
                            result.error("invalid_phone_number", "Phone number is required", null);
                        }
                    } else {
                        result.notImplemented();
                    }
                }
        );

    }

    private void sendMessageToFlutter(Map message) {
        holdUpMethodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), HOLD_UP_CHANNEL);
        holdUpMethodChannel.invokeMethod("onTelephonyEvent", message, new MethodChannel.Result() {
            @Override
            public void success(Object result) {
                // 调用成功时的回调
                Log.i("===", message + "成功了哈哈哈哈哈");
            }

            @Override
            public void error(String errorCode, String errorMessage, Object errorDetails) {
                // 调用失败时的回调
                Log.i("===", "失败了呜呜呜");
                Log.i("===", errorMessage);
            }

            @Override
            public void notImplemented() {
                // 调用未实现时的回调
                Log.i("===", "没调用啊");
            }
        });
    }


    private void dialPhoneNumber(String phoneNumber) {
        //	用户未授权过申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG, Manifest.permission.CALL_PHONE},
                    1);
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
                isStart = true;
                Map<String, Object> map = new HashMap();
                map.put("msg", "call_hold");
                sendMessageToFlutter(map);
            }

        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("===", "onRestart");
        if (isStart) {
            Map<String, Object> map = new HashMap();
            map.put("msg", "call_up");
            map.put("duration", getCallLog());
            sendMessageToFlutter(map);
            isStart = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (callMethodChannel != null) {
            callMethodChannel = null;
        }
        if (holdUpMethodChannel != null) {
            holdUpMethodChannel = null;
        }

    }


    private void badgeNumberChannel() {
        String brand = android.os.Build.BRAND;
        if ("oppo".equalsIgnoreCase(brand)) {
            bdgeNumberMethodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), BDGENUM_CHANNEL);
            bdgeNumberMethodChannel.setMethodCallHandler(
                    (call, result) -> {
                        if (call.method.equals("setBadgeNumber")) {
                            int number = call.argument("number");
                            if (number != 0) {
                                setBadgeNumber(number);
                                result.success(null);
                            } else {
                                result.error("invalid_phone_number", "Phone number is required", null);
                            }
                        } else {
                            result.notImplemented();
                        }
                    }
            );
        }
    }

    public  boolean canResolveBroadcast(Intent intent) {
        PackageManager packageManager = getPackageManager();
        List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(intent, 0);
        return receivers != null && receivers.size() > 0;
    }

    public  void setBadgeNumber(int number) {
        if (number == 0) number = -1;
        try {
            Bundle extras = new Bundle();
            extras.putInt("app_badge_count", number);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                getContentResolver().call(Uri.parse("content://com.android.badge/badge"), "setAppBadgeCount", null, extras);
                System.out.println("========================s================成功了"+number);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
//        try {
//
//            if (number == 0) number = -1;
//            Intent intent = new Intent("com.oppo.unsettledevent");
//            intent.putExtra("pakeageName", getPackageName());
//            intent.putExtra("number", number);
//            intent.putExtra("upgradeNumber", number);
//            if (canResolveBroadcast(intent)) {
//                sendBroadcast(intent);
//            } else {
//
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
    }
}